package com.party.mobile.web.controller.article;

import com.google.common.base.Strings;
import com.google.common.collect.Maps;
import com.party.authorization.annotation.Authorization;
import com.party.common.constant.Constant;
import com.party.common.paging.Page;
import com.party.common.utils.LangUtils;
import com.party.common.utils.PartyCode;
import com.party.common.utils.StringUtils;
import com.party.core.exception.BusinessException;
import com.party.core.model.BaseModel;
import com.party.core.model.YesNoStatus;
import com.party.core.model.article.Article;
import com.party.core.model.channel.Channel;
import com.party.core.model.member.Member;
import com.party.core.model.member.MemberGroup;
import com.party.core.model.serviceguide.ServiceGuideType;
import com.party.core.model.subject.SubjectApply;
import com.party.core.model.system.TargetType;
import com.party.core.service.article.IArticleService;
import com.party.core.service.channel.IChannelService;
import com.party.core.service.member.IMemberGroupService;
import com.party.core.service.member.IMemberService;
import com.party.core.service.serviceguide.IServiceGuideTypeService;
import com.party.core.service.subject.ISubjectApplyService;
import com.party.mobile.biz.article.ArticleBizService;
import com.party.mobile.biz.article.ArticleGroupBizService;
import com.party.mobile.biz.currentUser.CurrentUserBizService;
import com.party.mobile.web.annotation.VisitCollect;
import com.party.mobile.web.dto.AjaxResult;
import com.party.mobile.web.dto.article.output.ArticleGroupOutput;
import com.party.mobile.web.dto.article.output.ArticleListOutput;
import com.party.mobile.web.dto.article.output.ArticleOutput;
import com.party.mobile.web.dto.channel.ChannelOutput;
import com.party.mobile.web.dto.distributor.input.GetDistributorInput;
import com.party.mobile.web.dto.login.output.CurrentUser;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.ibatis.annotations.Param;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * 文章控制层
 * party
 * Created by Wesley
 * on 2016/11/21
 */

@Controller
@RequestMapping(value = "/article/article")
public class ArticleController {

    @Autowired
    IArticleService articleService;

    @Autowired
    IChannelService channelService;

    @Autowired
    ArticleGroupBizService articleGroupBizService;

    @Autowired
    CurrentUserBizService currentUserBizService;

    @Autowired
    IMemberService memberService;

    @Autowired
    ArticleBizService articleBizService;

    @Autowired
    IServiceGuideTypeService serviceGuideTypeService;

    @Autowired
    private IMemberGroupService memberGroupService;

    @Autowired
    private ISubjectApplyService subjectApplyService;

    Logger logger = LoggerFactory.getLogger(getClass());


    /**
     * 分页查询文章列表
     *
     * @param articleType 文章类型
     * @param page        分页参数
     * @return 交互数据
     */
    @ResponseBody
    @RequestMapping(value = "/list")
    public AjaxResult list(String articleType, Page page, String channelid, String order, String articleGroupId) {

//        if (Strings.isNullOrEmpty(articleType) || Integer.parseInt(articleType) < 1 || Integer.parseInt(articleType) > 3)
//        {
//            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数不合法");
//        }
        Article article = new Article();
        article.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        article.setArticleType(articleType);
        if (StringUtils.isNotEmpty(channelid)) {
            Channel channel = new Channel();
            channel.setId(channelid);
            article.setChannel(channel);
        }
        if (StringUtils.isNotEmpty(articleGroupId)) {
            article.setArticleGroupId(articleGroupId);
        }
        article.setOrderBy(order);
        List<Channel> channels = new ArrayList<>();
        if (StringUtils.isNotEmpty(articleGroupId)) {
            SubjectApply apply = subjectApplyService.findByTargetId(articleGroupId);
            //获取栏目下频道类别
            Channel channel = new Channel();
            channel.setMember(apply.getId());
            channel.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
            channels = channelService.listPage(channel, null);
        }

        //不用分类
        if (channels.size() == 1 || channels.size() == 0) {
            List<Article> articleList = articleService.listPage(article, page);
            if (!CollectionUtils.isEmpty(articleList)) {
                List<ArticleListOutput> outputList = LangUtils.transform(articleList, input -> {
                    ArticleListOutput output = ArticleListOutput.transform(input);

                    //设置分享链接
                    output.setShareLink(getShareLink(input.getId()));

                    //判断是文章还是分类
                    output.setIsArticle(YesNoStatus.YES.getCode());
                    return output;
                });
                return AjaxResult.success(outputList, page);
            }
        } else if (StringUtils.isEmpty(channelid)){
            if (!CollectionUtils.isEmpty(channels)) {
                SubjectApply apply = subjectApplyService.findByTargetId(articleGroupId);
                //获取栏目下频道类别
                Channel channel = new Channel();
                channel.setMember(apply.getId());
                channel.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                List<Channel> channels2 = channelService.listPage(channel, page);
                List<ChannelOutput> outputList = LangUtils.transform(channels2, input -> {
                    ChannelOutput output = ChannelOutput.transform(input);

                    article.setChannel(input);

                    List<Article> articles = articleService.listPage(article, null);
                    output.setArticleNum(articles.size());

                    output.setIsCategory(YesNoStatus.YES.getCode());
                    return  output;
                });
                return AjaxResult.success(outputList, page);
            }
        } else {
            List<Article> articleList = articleService.listPage(article, page);
            if (!CollectionUtils.isEmpty(articleList)) {
                List<ArticleListOutput> outputList = LangUtils.transform(articleList, input -> {
                    ArticleListOutput output = ArticleListOutput.transform(input);

                    //设置分享链接
                    output.setShareLink(getShareLink(input.getId()));

                    //判断是文章还是分类
                    output.setIsArticle(YesNoStatus.YES.getCode());
                    return output;
                });
                return AjaxResult.success(outputList, page);
            }
        }
        return AjaxResult.success(Collections.EMPTY_LIST, page);
    }

    /**
     * 获取文章详情
     *
     * @param id 文章主键id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getDetails")
    @VisitCollect(module = TargetType.ARTICLE)
    public AjaxResult getDetails(String id, HttpServletRequest request) {
        if (Strings.isNullOrEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数不合法");
        }
        Article article = articleService.get(id);
        if (null == article || null == article.getContent() || article.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "文章不存在");
        }

        ArticleOutput output = ArticleOutput.transform(article);

        //设置文章内容
        output.setContent(StringEscapeUtils.unescapeHtml4(article.getContent()));
        //设置分享链接
        output.setShareLink(getShareLink(id));

        article.setReadNum(article.getReadNum() + 1);
        articleService.update(article);
        if (article.getChannel() != null && article.getChannel().getId() != null) {
            Channel channel = channelService.get(article.getChannel().getId());
            if (channel != null) {
                output.setChannelId(channel.getId());
                output.setChannelName(channel.getName());
            }
        }
        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        MemberGroup creator = memberGroupService.get(article.getMemberId());
        output.setIsPartner(creator.getIsPartner());
        output.setCreateByName(creator.getRealname());
        output.setCreateDate(article.getCreateDate());
        //是否允许分销
        if (null != currentUser) {
            if (!currentUser.getId().equals(article.getMemberId())) {
                if (null != currentUser.getIsMemberGroup()) {
                    if (YesNoStatus.YES.getCode().equals(currentUser.getIsMemberGroup())) {
                        output.setIsDistributor(0);
                    } else if (YesNoStatus.NO.getCode().equals(currentUser.getIsMemberGroup())) {
                        Member member = memberService.get(currentUser.getId());
                        output.setIsDistributor(member.getIsDistributor());
                    }
                }
            } else {
                output.setIsDistributor(Constant.BAN_DISTRIBUTION);
            }
        }
        return AjaxResult.success(output);
    }

    @ResponseBody
    @RequestMapping(value = "/articlegroup/detail")
    @VisitCollect(module = TargetType.ARTICLE)
    public AjaxResult getArticleGroupDetails(String id, HttpServletRequest request) {
        if (Strings.isNullOrEmpty(id)) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数不合法");
        }

        try {
            ArticleGroupOutput output = articleGroupBizService.getDetails(id, request);
            return AjaxResult.success(output);
        } catch (BusinessException be) {
            return AjaxResult.error(be.getCode(), be.getMessage());
        }
    }


    /**
     * 获取文章分销详情
     *
     * @param input   输入视图
     * @param request 请求参数
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/distribution/detail")
    public AjaxResult getDistributorDetails(HttpServletRequest request, GetDistributorInput input) {
        if (Strings.isNullOrEmpty(input.getTargetId())) {
            return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "参数不合法");
        }
        Article article = articleService.get(input.getTargetId());
        if (null == article || null == article.getContent() || article.getDelFlag().equals("1")) {
            return AjaxResult.error(PartyCode.IS_NO_DATA, "文章内容不存在");
        }

        ArticleOutput output = ArticleOutput.transform(article);

        //设置文章内容
        output.setContent(StringEscapeUtils.unescapeHtml4(article.getContent()));
        //设置分享链接
        output.setShareLink(getShareLink(input.getTargetId()));

        article.setReadNum(article.getReadNum() + 1);
        articleService.update(article);
        if (article.getChannel() != null && article.getChannel().getId() != null) {
            Channel channel = channelService.get(article.getChannel().getId());
            if (channel != null) {
                output.setChannelId(channel.getId());
                output.setChannelName(channel.getName());
            }
        }

        CurrentUser currentUser = currentUserBizService.getCurrentUser(request);
        output = articleBizService.getDistributionDetails(output, input, currentUser);
        return AjaxResult.success(output);
    }


    /**
     * 获取文章分享链接
     *
     * @param id 文章主键id
     * @return
     */
    private String getShareLink(String id) {
        return "http://3g.tongxingzhe.cn/micWeb/html/article/article_detail.html?id=" + id;
    }

    /**
     * 服务指南列表
     *
     * @param request
     * @param page    分页
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getServiceList")
    public AjaxResult getServiceList(HttpServletRequest request, Page page) {
        try {
            String memberId = currentUserBizService.getCurrentUser(request).getId();
            List<Article> articleList = articleService.getServiceList(memberId, page);
            if (!CollectionUtils.isEmpty(articleList)) {
                List<ArticleListOutput> outputList = LangUtils.transform(articleList, input -> {
                    ArticleListOutput output = ArticleListOutput.transform(input);
                    return output;
                });
                return AjaxResult.success(outputList, page);
            }
            return AjaxResult.success(Collections.EMPTY_LIST, page);
        } catch (Exception e) {
            logger.error("服务指南列表", e);
            return AjaxResult.error(100, "服务指南列表");
        }
    }


    /**
     * 服务指南类型列表
     *
     * @param request
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("getServiceGuideList")
    public AjaxResult getServiceGuideList(HttpServletRequest request) {
        try {
            String memberId = currentUserBizService.getCurrentUser(request).getId();
            String getPartnerId = memberGroupService.getPartnerId(memberId);
            List<Map<String, Object>> list = serviceGuideTypeService.queryGuideTypeListBymemberId(getPartnerId);
            return AjaxResult.success(list);
        } catch (Exception e) {
            logger.error("服务指南类型列表", e);
            return AjaxResult.error(100, "服务指南类型列表");
        }
    }


    /**
     * new_服务指南列表
     *
     * @param request
     * @param page    分页
     * @return
     */
    @ResponseBody
    @Authorization
    @RequestMapping("new/getServiceList")
    public AjaxResult getnewServiceList(HttpServletRequest request, String guideTypeId, Page page) {
        try {
            if (Strings.isNullOrEmpty(guideTypeId)) {
                return AjaxResult.error(PartyCode.PARAMETER_ILLEGAL, "指南类型id为空");
            }
            ServiceGuideType serviceGuideType = serviceGuideTypeService.get(guideTypeId);
            if (serviceGuideType == null) {
                return AjaxResult.error(PartyCode.DATA_IS_BE_DELETE, "指南类型不存在");
            }
            String memberId = currentUserBizService.getCurrentUser(request).getId();
            String partnerId = memberGroupService.getPartnerId(memberId);
            List<Article> articleList = articleService.getServiceListByGuideId(partnerId, guideTypeId, page);
            if (!CollectionUtils.isEmpty(articleList)) {
                List<ArticleListOutput> outputList = LangUtils.transform(articleList, input -> {
                    ArticleListOutput output = ArticleListOutput.transform(input);
                    return output;
                });
                return AjaxResult.success(outputList, page);
            }
            return AjaxResult.success(Collections.EMPTY_LIST, page);
        } catch (Exception e) {
            logger.error("new_服务指南列表", e);
            return AjaxResult.error(100, "new_服务指南列表");
        }
    }
}
